package com.ljx.NoteBody.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ljx.NoteBody.entity.User;

import java.util.Calendar;


public class TokenUtil {

    private static String myPassword = "lijunxinb!1561sf99hnfw123ioHOH[].,miQFNJibr@#DN@#$%^";

    /**
     * 生成token
     */
    public static String getToken(User u) {
        Calendar instance = Calendar.getInstance();
        // 默认令牌过期时间7天
        instance.add(Calendar.DATE, 3);

        JWTCreator.Builder builder = JWT.create();
        // 对账号加密
        builder.withClaim("username", u.getUsername());

        return builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(myPassword));
    }

    /**
     * 验证token合法性 成功返回token
     */
    public static DecodedJWT verify(String token) {
        JWTVerifier build = JWT.require(Algorithm.HMAC256(myPassword)).build();
        return build.verify(token);
    }

}
